package com.yinhe.music.yhmusic.base;


import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;

import com.yinhe.music.yhmusic.log.MLog;
import com.yinhe.music.yhmusic.service.PlayService;

/**
 * Created by Johnson on 2017/10/17.
 */

public class BaseDialoagFragment extends DialogFragment implements IServiceConnect {


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        bindService();
    }

    @Override
    public void onDetach() {
        unBindService();
        super.onDetach();
    }


    @Override
    public void show(FragmentManager manager, String tag) {
        try {
            //在每个add事务前增加一个remove事务，防止连续的add
            manager.beginTransaction().remove(this).commit();
            super.show(manager, tag);
        } catch (Exception e) {
            //同一实例使用不同的tag会异常,这里捕获一下
            e.printStackTrace();
        }
    }

    private static final String TAG = "BaseDialoagFragment";

    protected PlayService mService;
    private ServiceConnection servConn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mService = ((PlayService.PlayBinder) service).getService();
            BaseDialoagFragment.this.onServiceConnected(mService);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mService = null;
            BaseDialoagFragment.this.onServiceDisconnected();
        }
    };

    @Override
    public void bindService() {
        if (servConn == null) {
            return;
        }

        Intent intent = new Intent();
        intent.setClass(getActivity(), PlayService.class);
        getActivity().bindService(intent, servConn, Context.BIND_AUTO_CREATE);
    }

    @Override
    public void unBindService() {
        if (servConn != null) {
            getActivity().unbindService(servConn);
            servConn = null;
        }
    }

    public void onServiceConnected(PlayService service) {

    }

    protected void onServiceDisconnected() {

    }
}
